// pages/sceneTaskDetail/index.js
const api = require('../../config/api')
const request = require('../../utils/request')
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    trainingId: '', // 场景训练任务详情
    article: '', // 文章详情
    detail: '', // 任务详情
    sceneList: [], // 推荐训练列表
    posterSrc:
      'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend3112705936ec4679ad331a5d1cac2faf.png', // 海报图片
    showPoster: false,
    hadLogin: true, // 判断是否已登录
    hadCollect: false, // 判断是否收藏
    shareInfo: {},
    collectionId: '', // 收藏id
    htmlContent: '',
    bottomHeight: app.kBottomSafeHeight + 112,
    modalHeight: app.kBottomSafeHeight + 345,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let id = ''
    if (options.trainingId) {
      id = options.trainingId
    } else {
      id = wx.getStorageSync('trainingId')
    }

    this.getTrainDetail(id)
    this.getShareInfo(id)
    this.setData({
      trainingId: id,
    })
  },
  onShow: function () {
    let { trainingId } = this.data
    if (app.isLogin()) {
      this.checkCollect(trainingId)
    }
    this.setData({
      hadLogin: app.isLogin(),
    })
  },
  // 获取训练模版详情
  getTrainDetail: async function (trainingId) {
    const res = await request.get(
      api.trainingDetail + trainingId,
      {},
      { loading: false }
    )
    if (res.httpStatus === 200) {
      wx.setNavigationBarTitle({
        title: res.data.trainingName,
      })

      let htmlContent = res.data.description

      this.setData({
        detail: res.data,
        sceneList: res.data?.templateVOS,
        htmlContent: htmlContent,
      })
    }
  },
  // 检查是否收藏
  async checkCollect(trainingId) {
    const res = await request.get(
      api.checkCollect + trainingId,
      {},
      { loading: false }
    )
    if (res.httpStatus === 200) {
      this.setData({
        hadCollect: res.data ? true : false,
        collectionId: res.data,
      })
    }
  },
  async getShareInfo(trainingId) {
    const res = await request.get(
      api.shareTrainInfo + trainingId,
      {},
      { loading: false }
    )
    if (res.httpStatus === 200) {
      this.setData({
        shareInfo: res.data,
      })

      if (res.data.posterImageUrl) {
        this.setData({
          posterSrc: res.data.posterImageUrl,
        })
      }
    }
  },
  handleSceneTrainDetail(e) {
    let trainingId = e.currentTarget.dataset.id

    if (trainingId === this.data.trainingId) {
      return
    }
    this.getTrainDetail(trainingId)
    this.checkCollect(trainingId)
    this.getShareInfo(trainingId)
    this.setData({
      trainingId: trainingId,
    })
  },
  onReady: function () {
    this.shareSheet = this.selectComponent('#shareSheet')
  },
  // 显示分享弹窗
  showShareSheet() {
    this.setData({
      showPoster: true,
    })
    this.shareSheet.show()
  },
  // 隐藏分享弹窗
  hideShareSheet() {
    this.setData({
      showPoster: false,
    })
    this.shareSheet.hide()
  },
  // 收藏与取消收藏
  async handleCollect() {
    let { trainingId, shareInfo, collectionId, hadCollect } = this.data
    // isTemplate-- 模板类型 1-模板 0-非模板
    let bindBeforeId =
      shareInfo.isTemplate === 1 ? shareInfo.trainingId : shareInfo.bindBeforeId

    if (!app.isLogin()) {
      app.globalData.isJoinedLogin = false
      const url = `/pages/sceneTrainDetail/index?trainingId=${trainingId}&collect=1`
      wx.setStorageSync('trainingId', bindBeforeId)
      wx.setStorageSync('collect', 1)
      app.navTo(url)
      return
    }
    let res = null
    if (!hadCollect) {
      res = await request.post(
        api.collectTrain + bindBeforeId,
        {},
        { loading: false }
      )
    } else {
      res = await request.post(
        api.unCollectTrain + collectionId,
        {},
        { loading: false }
      )
    }
    if (res.httpStatus === 200) {
      setTimeout(() => {
        wx.showToast({
          title: hadCollect ? '取消收藏成功' : '收藏成功',
          icon: 'success',
        })
      }, 300)

      if (!hadCollect) {
        wx.vibrateShort({
          type: 'light',
        })
        this.setData({
          collectionId: res.data,
        })
      }
      this.checkCollect(trainingId)
    }
  },
  // 保存图片到相册
  savePic: function () {
    let that = this
    let { posterSrc } = this.data
    wx.getImageInfo({
      src: posterSrc,
      success: function (sres) {
        wx.saveImageToPhotosAlbum({
          filePath: sres.path,
          success: function (fres) {
            that.hideShareSheet()
            wx.showToast({
              title: '保存成功',
              icon: 'success',
            })
          },
          fail: function (fres) {
            wx.showToast({
              title: '保存失败',
              icon: 'error',
            })
          },
        })
      },
    })
  },
  // 加入训练
  async handleJoin() {
    let { trainingId, shareInfo } = this.data
    // isTemplate-- 模板类型 1-模板 0-非模板
    let bindBeforeId =
      shareInfo.isTemplate === 1 ? shareInfo.trainingId : shareInfo.bindBeforeId

    if (!app.isLogin()) {
      app.globalData.isJoinedLogin = false
      const url = `/pages/sceneTrainDetail/index?trainingId=${trainingId}`
      wx.setStorageSync('trainingId', bindBeforeId)
      wx.setStorageSync('collect', 0)
      app.navTo(url)
      return
    }

    let patientInfo = wx.getStorageSync('patientInfo')
    if (!patientInfo) {
      app.globalData.isJoinedLogin = true
      app.globalData.createPatientEntrance = 5
      wx.setStorageSync('trainingId', bindBeforeId)
      wx.navigateTo({
        url: '/pages/createPatient/select/select',
      })
      return
    }
    app.globalData.createPatientEntrance = ''
    const res = await request.post(
      api.joinTraining,
      {
        bindBeforeId: bindBeforeId,
        patientId: patientInfo.id,
      },
      { loading: false }
    )
    if (res.httpStatus === 200) {
      let { startDate, trainingName, endDate } = res.data.trainingTemplateInfo
      let { detailId, trainingType, questionnaireId } =
        res.data.trainingDetailInfo
      let trainingId1 = res.data.trainingDetailInfo.trainingId
      let { isNeedEject } = res.data
      wx.navigateTo({
        url: `/pages/practiceJoin/index?startDate=${startDate}&endDate=${endDate}&trainingId=${trainingId1}&trainingName=${trainingName}&detailId=${detailId}&trainingType=${trainingType}&questionnaireId=${questionnaireId}&isNeedEject=${isNeedEject}`,
      })
    } else {
      setTimeout(() => {
        wx.showToast({
          title: res.msg ? res.msg : '加入失败',
          icon: 'none',
        })
      }, 200)
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let { shareInfo, trainingId } = this.data
    return {
      title: shareInfo.trainingName,
      path: '/pages/sceneTrainDetail/index?trainingId=' + trainingId,
      imageUrl:
        shareInfo.shareImageUrl ||
        'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend5d6c29cf96f348d08c6a56d83a995686.png',
    }
  },
})
